package tralala.jdo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import tralala.data.*;



public class ReproduccionDAO implements Serializable{
	private PersistenceManager pm = null;
	private PersistenceManagerFactory pmf=null;
	private static ReproduccionDAO cd= new ReproduccionDAO();
	
	private ReproduccionDAO() {
		System.out.println("Constructor ReproduccionDAO");
		pmf = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");
		pm=pmf.getPersistenceManager();
	}
	
	public static ReproduccionDAO getInstance(){
		return cd;
	}
	
	
	public void almacenar(Reproduccion play){
		Transaction tx = pm.currentTransaction();
		try{
		tx.begin();
		pm.makePersistent(play);
		tx.commit();
		}
		catch(Exception ex)
		{
			ex.getMessage();
			System.out.println("EXCEPCION AL ALMACENAR REPRODUCCION");
		}
	}
	
	public void remove(Reproduccion play){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		pm.deletePersistent(play);
		tx.commit();
	}
	
	
	public List<Reproduccion> obtenerReproducciones(String login){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		
		Query q = pm.newQuery("SELECT FROM " + Reproduccion.class.getName()); 
		@SuppressWarnings("unchecked")
		List<Reproduccion> listPlays = (List<Reproduccion>) q.execute();
		tx.commit();
		System.out.println(listPlays.size());
		List<Reproduccion> aux = new ArrayList<Reproduccion> ();
		for(int i=0;i<listPlays.size();i++){
			if(listPlays.get(i).getUs().getNombre_usuario().equals(login)){
				aux.add(listPlays.get(i));
			}
		}
		return aux;
	}
	
	public int cntabilizarReproducciones(String login){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		
		Query q = pm.newQuery("SELECT FROM " + Reproduccion.class.getName()); 
		@SuppressWarnings("unchecked")
		List<Reproduccion> listPlays = (List<Reproduccion>) q.execute();
		tx.commit();
		System.out.println(listPlays.size());
		List<Reproduccion> aux = new ArrayList<Reproduccion> ();
		for(int i=0;i<listPlays.size();i++){
			if(listPlays.get(i).getUs().getNombre_usuario().equals(login)){
				aux.add(listPlays.get(i));
			}
		}
		return aux.size();
	}
}
